import Api from '../service/Api';
import {emojiArr} from './Emoji';
import JsBrdige from '../service/JsBridge';
import ChatManager from '../component/ChatManager';
import JsBridge from '../service/JsBridge';



/**
 * 发送文本转换 <br /> -> \n  &nbsp; -> ' '
 * @param  {[type]} content [description]
 * @return {[type]}         [description]
 */
export function sendTextFmt(content) {
  let outstr = content;
  // <br /> -> \n
  outstr = outstr.replace(/<br\s\/>/gm, '\n');

  // &nbsp; -> ' '
  outstr = outstr.replace(/&nbsp;/gm, ' ');

  return outstr;

}

/**
 * 接受文本转换 \n -> <br />  ' ' -> &nbsp;
 * @param  {[type]} content [description]
 * @return {[type]}         [description]
 */
export function receiveTextFmt(content) {
  let outstr = content;
  // <br /> -> \n
  outstr = outstr.replace(/\\n/gm, '<br />');

  // // &nbsp; -> ' '
  // outstr = outstr.replace(/\s/gm, '&nbsp;');

  return outstr;

}


/**
 * 时间格式化函数
 * @param  {[moment]} m1 [moment实例 将要格式化的实例]
 * @param  {[moment]} m2 [moment实例 作为比较的实例]
 * @param  {[Boolean]} isLeft [区分是左边的消息列表中的时间与否]
 * @return {[String]}    [m1格式化之后的实例]
 */
export function chatTimeFormat(m1, m2, isLeft) {
  let days = Math.ceil(Math.abs(m1.diff(m2, 'days', true))) // 相差天数
  if (m1.isSame(m2, 'day')) { // 当天的消息
    return m1.format('a HH:mm')
  } else if (days < 2) { // 昨天的消息
    return isLeft ?
    m1.format('昨天 HH:mm')
    : m1.format('昨天 a HH:mm')
  } else { // 大于昨天的消息
    return isLeft ?
    m1.format('MM-DD') // 列表只需显示日期
    : m1.format('YYYY年MM月DD日 a HH:mm') // 对话中需要显示详情
  }
}

// 全局禁止事件
export function forbidEvent() {
  $('body').css('pointer-events', 'none');
}
// 全局恢复事件
export function allowEvent() {
  $('body').css('pointer-events', 'all');
}

export function serverLogin(unitUrl, user, password,unitUrl2) {
  let deferred = $.Deferred();
  console.log(unitUrl)
  console.log(unitUrl2)
  $.ajax({
    url: unitUrl + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
    type: "post",
    dataType: "json",
    data: {
      LoginID: user,
      EncyptPassword: password,
      OnlineType: 130,
      DeviceName: 'web test',
      Place: 'cs'
    },
    success: function (json) {
      if (json.Goodo.UserName) {

        JsBrdige.sendRequest('user.login', {
          userInfo: json.Goodo,
          LoginID: user,
          EncyptPassword: password,
          UnitUrl: unitUrl,
           UnitUrl2: unitUrl2,
          UnitName: json.Goodo.UnitName
        });

        localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));

        location.href = `index.html?burl=${unitUrl}`; // 跳转到首页

        deferred.resolve(true)
      } else {
        deferred.resolve(false)
      }
    },
    error: function(err) {
      deferred.resolve(false)
    }
  });

  return deferred;
}

export function login_way(url ,url2) {
  $(".login").unbind("click");
  $(".login").click(function () {                         /////登录
    let user = $("#user").val();
    let pass = $("#pass").val();

    layer.msg('正在登陆', {
      time: 0
    });

    JsBridge.sendRequest("user.password", {password: pass}).then(resp => {
      $.ajax({
        url: url + '/BasePlate/Interface/IInterfaceJson.asmx/LoginUser',
        type: "post",
        dataType: "json",
        data: {
          LoginID: user,
          EncyptPassword: resp.data.password,
          OnlineType: 130,
          DeviceName: 'web test',
          Place: 'cs'
        },
        success: function (json) {

          // console.log(json.Goodo.UserName);
          layer.closeAll();

//        alert(111);
          JsBridge.sendRequest("custom.get", {key: 'yxtLog'}).then(jsrep => {
//            alert(JSON.stringify(jsrep));

              let cookie_log = jsrep.data.value;
              let logs = [];
              if (cookie_log) {
                logs = JSON.parse(cookie_log).logs;
              }

              if (json.Goodo.UserName) {
                $(".login").unbind("click");
                //Cookies.set("yxtUser", json.Goodo);
                console.log(url2)
                console.log(json)
                JsBrdige.sendRequest('user.login', { userInfo: json.Goodo, LoginID: user, EncyptPassword: resp.data.password, UnitUrl: url,UnitUrl2: url2, UnitName: json.Goodo.UnitName });

                localStorage.setItem("yxtUser", JSON.stringify(json.Goodo));
                // 找出同单位同姓名的记录并删除
                let { Unit_ID, UnitName, UserName, User_ID } = json.Goodo;
                let repeatIndex;
                for (let i = 0; i < logs.length; i++) {
                  if (logs[i].Unit_ID === Unit_ID && logs[i].User_ID === User_ID) {
                    repeatIndex = i;
                    break;
                  }
                }
                repeatIndex >= 0 && logs.splice(repeatIndex, 1); // 去重
                logs.unshift({ Unit_ID, UnitName, UserName, User_ID, UnitUrl: url,UnitUrl2: url2, user, pass }); // 添加新记录
                JsBridge.sendRequest("custom.set", {key: 'yxtLog', value: JSON.stringify({ "logs": logs })}) // 添加到本地

                location.href = `index.html?burl=${url}`; // 跳转到首页
              } else {
                layer.msg(`${json.Goodo.ErrorMessage}`);
              }
          });

        },
        error: function (err) {
          layer.closeAll();
          layer.msg('网络请求超时出错');
          // console.log(err);
        }
      });
    })

  });
}



/**
 * 消息选择人页面获取多级列表
 * @param  {[Object]} url: {
 *                      url: String, [多级列表请求地址]
 *                      paramsName: String, [额外参数名]
 *                    }
 * @param  {[fn]} success [请求成功后的回调 传入一个data数组，数组元素为对象并包含一个'_c'属性 '_c'为二级栏目数组]
 * @return {[Object]} lv_1 {data: Array}  data数组，数组元素为对象并包含或不包含一个'_c'属性 '_c'为当前子级栏目数组
 */
export function multiData({url}) {
  const { User_ID, Unit_ID, SessionID } = JSON.parse(localStorage.getItem("yxtUser"));
  let lv_1 = {data: []};
  const dfd = $.Deferred();
  let fetchNum = 0;

  let digui = function(father, params, root) {
    fetchNum++;
    // console.log('调用', fetchNum);
    Api.get(`/BasePlate/Interface/IInterfaceJson.asmx${url.url}`, $.extend({}, { User_ID, Unit_ID, SessionID }, params))  // 获取一级栏目
    .then(resp => {
      if (resp && resp.Goodo && resp.Goodo.R) { // 获取一级栏目成功
        if (root) {
          father.data = resp.Goodo.R;
        } else {
          father._c = resp.Goodo.R;
        }
        for (let i = 0; i < resp.Goodo.R.length; i ++) {

//        if (resp.Goodo.R[i].ID == User_ID) { // 删掉登陆者
//          delete father._c[i];
//          continue;
//        }
          if (root) {
            if (father.data[i].ID > 0) {
              continue;
            } else {
              let e_p = {};
              e_p[url.paramsName] = father.data[i].ID.slice(1);
              digui(father.data[i], e_p);
            }
          } else {
            if (father._c[i].ID > 0) {
              continue;
            } else {
              let e_p = {};
              e_p[url.paramsName] = father._c[i].ID.slice(1);
              digui(father._c[i], e_p);
            }
          }

        }
        return;
      } else {
        // console.log(`获取栏目失败或为空`)
      }
    }).done(() => {
      fetchNum--;
      // console.log('完成', fetchNum);
    })
  };

  let params = {};
  params[url.paramsName] = 0;
  digui(lv_1, params, true);

  let timer = window.setInterval(() => {
    if(lv_1.data.length > 0 && fetchNum == 0) { // 取到数据 且所有请求已经完成
      window.clearInterval(timer);
      dfd.resolve(lv_1);
    }
  }, 200)
  return dfd;
}

/**
 * 消息选择人页面获取多级列表 -- 个人群组
 * @param  {[Object]} url: {
 *                      url: String, [多级列表请求地址]
 *                      paramsName: String, [额外参数名]
 *                    }
 * @param  {[fn]} success [请求成功后的回调 传入一个data数组，数组元素为对象并包含一个'_c'属性 '_c'为二级栏目数组]
 * @return {[Object]} lv_1 {data: Array}  data数组，数组元素为对象并包含或不包含一个'_c'属性 '_c'为当前子级栏目数组
 */
export function multiData2({url}) {
  const { User_ID, Unit_ID, SessionID } = JSON.parse(localStorage.getItem("yxtUser"));
  let lv_1 = {data: []};
  const dfd = $.Deferred();
  let fetchNum = 0;

  let URILs = [
    `/MyGroup_GetList` // 个人群组列表
  ]

  // 获取个人群组列表
  Api.get(`/BasePlate/Interface/IInterfaceJson.asmx${URILs[0]}`, {User_ID, SessionID, Unit_ID})
  .then(resp => {
    console.log(`---------------person`);
    console.log(resp);
    if (resp && resp.Goodo && resp.Goodo.R) {
        const lists = resp.Goodo.R;
        lists.forEach(item => {
          item.ID = `-${item.Group_ID}`;
          item._c = []; // 预备存储组下成员数组
          lv_1.data.push(item);
        });

        // 开始查询组下成员
        lv_1.data.forEach(item => {
          fetchNum++;
          Api.get(`/BasePlate/Interface/IInterfaceJson.asmx${url.url}`, {User_ID, SessionID, Unit_ID, Group_ID: item.Group_ID})
          .then(rresp => {
            fetchNum--;
            if (rresp && rresp.Goodo && rresp.Goodo.R) {
              item._c = rresp.Goodo.R;
            } else {
              console.log(`获取${item.GroupName}的成员失败`);
            }
          })
        })

        let timer = window.setInterval(() => {
          if(lv_1.data.length > 0 && fetchNum == 0) { // 取到数据 且所有请求已经完成
            window.clearInterval(timer);
            dfd.resolve(lv_1);
          }
        }, 200)

    } else {
      console.log(`获取个人群组列表失败`)
    }
  })

  return dfd;
}

// [emoji] -> <img />(emoji)
export function emojiString(str) {

  let transform = function(match, p1, offset, string) {
    let output = p1;
    // p1 --- [xxx]
    for (let i = 0; i < emojiArr.length; i++) {
      // console.log(`p1-----------${p1}------------emoji-----------${emojiArr[i].key}`)
      if (p1 === emojiArr[i].key) {
        // console.log(`---------匹配成功------------`)
        output = `<img class='emoji' src='img/Emoticon/${emojiArr[i].value}' />`;
        break;
      }
    }
    return output;
  }

  return str.replace(/(\[[^\]]+\])/g, transform)
}

// <img />(emoji) -> [emoji]  | <img /> -> ''
export function emoImgToRect(str) {

  let transform = function(match, p1, offset, string) {
    let output = match;
    // p1 --- xxxx.png;
    for (let i = 0; i < emojiArr.length; i++) {
      // console.log(`p1-----------${p1}------------emoji-----------${emojiArr[i].key}`)
      if (p1 === emojiArr[i].value) {
        // console.log(`---------匹配成功------------`)
        output = `${emojiArr[i].key}`;
        break;
      }
    }
    return output;
  }

  return str.replace(/<img\s+(?:src=\"img\/Emoticon\/([^\s]+\.png)\")\s*(?:\/>)/g, transform).replace(/<img.*?(?:>|\/>)/g, "");
}

// array remove duplicate item
// return [unique: Arr, removedItem: Arr];
export function uniqueArr(arr) {
  let removedItem = [];
  let unique = arr.filter(function (item, pos) {
    if (arr.indexOf(item) == pos) {
      return true;
    } else {
      removedItem.push(item);
      return false;
    }
  });
  return [unique, removedItem];
}

// 从客户端拿去文件信息
export function addFileListener(obj, cb) {
  // 绑定事件
  $(obj).click(function(data) {

    forbidEvent();

    JsBrdige.sendRequest("file.read", {}).then(resp => {
      // console.log(data);
      if (!resp.success) { // 未取到相应文件就直接跳出
        allowEvent();
        return ;
      }

      resp.data.forEach(data => {
        if (!data.type) {
          data.type = fileType(data.fileName);
        }
        // 调取客户端的文件选择器
        let fileArr = window.fileArr;
        // 对当前文件列表和当前文件进行对比，文件名重复就不添加
        if (fileArr) {
          let isRepeat = false;
          for (let i = 0; i < fileArr.length; i++) {
            if (fileArr[i].fileName == data.fileName) {
              isRepeat = true;
              break;
            }
          };
          !isRepeat && window.fileArr.push(data);
        }
        // 从cb换回出相应的文件参数
        cb(data);
      });

    });

    return false;

  })
}

/**
 * 生成div块用于放入富文本编辑器中
 * @param  {[Object]} file [文件对象]
 * @return {[String]}      [HTML字符串]
 */
export function renderFileDiv(file) {

  let MsgType = fileType(file.fileName);

  switch (MsgType) {
    case 3:
      return `
        <div class="file file3" contenteditable="false">
          <p title="${file.fileName}"><img src="data:image/png;base64,${file.base64}"/></p>
        </div>
      `;
    case 4:
      return `
        <div class="file file4" contenteditable="false">
          <p title="${file.fileName}">${file.fileName}</p>
          <div class="finish"><p>发送完成</p><span>打开</span></div>
          <div class="progress">
						<div class="progress-bar" role="progressbar" aria-valuenow="60"
							 aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
							<p>发送中...(<span class="sr-only">40%</span>)</p><span>取消</span><span>暂停</span></div>
        </div>
      `;
    case 5:
      return `
        <div class="file file5" contenteditable="false">
          <p title="${file.fileName}">${file.fileName}</p>
          <div class="finish"><p>发送完成</p><span>打开</span></div>
          <div class="progress">
						<div class="progress-bar" role="progressbar" aria-valuenow="60"
							 aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
							<p>发送中...(<span class="sr-only">40%</span>)</p><span>取消</span><span>暂停</span></div>
        </div>
      `;
    default:
      return `
        <div class="file file2" contenteditable="false">
          <p title="${file.fileName}">${file.fileName}(<span>444kb</span>)</p>
          <div class="finish"><p>发送完成</p><span>打开</span></div>
          <div class="progress">
						<div class="progress-bar" role="progressbar" aria-valuenow="60"
							 aria-valuemin="0" aria-valuemax="100" style="width: 40%;"></div>
							<p>发送中...(<span class="sr-only">40%</span>)</p><span>取消</span><span>暂停</span></div>

			</div>
      `;
  }

}

/**
 * 对将要发送的文本进行过滤 将fileDiv剔除 并返回一个包含fileName的数组与过滤后的文本
 * @param  {[String]} str [将要发送的文本]
 * @return {[Arr]}     [一个包含fileName的数组与过滤后的文本]
 */
export function stringGetFileTitle(str) {
  let title = [];
  let format = function(match, p1, offset, string) {
    let _title;
    match.replace(/\btitle=\"([^\"]+)\"/g, function(match,p1) {
      _title = p1;
      return match;
    });
    // console.log(_title);
    if (_title) {
      title.push(_title);
      return '';
    } else {
      return match;
    }
  }

  let n_str = str.replace(/<div(([\s\S])*?)<\/div>/g, format);
  return [n_str, title];
}

/**
 * 混合发送
 * @param  {[type]} id       [用户id]
 * @param  {[type]} userName [接收者名]
 * @param  {[type]} content  [文本内容]
 * @param  {[type]} files    [文件名列表]
 * @return {[type]}          [异步Deferred]
 */
export function mixSend(id, userName, content, files, cbs = {}) {
  let up = cbs.up;
  let down = cbs.down;
  let count = files.length;
  let failFileSend = [];
  let d1 = $.Deferred(); // 文本发送
  let d2 = $.Deferred(); // 文件发送
  let dd = $.Deferred(); // 总信息传出
  // 发送文本
  if (content) {
    ChatManager.sendMessage(id, userName, content).then(messageId => {
        if (messageId === null) {
            d1.resolve(false);
        } else {
            // ChatManager.pollMessage();
            d1.resolve({mid: messageId, text: `文本发送成功`});
        }
    }, err => {alert('err');d1.resolve(false);})
  } else {
    d1.resolve(false);
  }
  // 发送文件
  if (count) {
    files.forEach(item => {
      window.fileArr.forEach(iitem => {
        if (iitem.fileName == item) {
          ChatManager.sendFile(id, userName, {type: iitem.type, fileName: iitem.fileName, base64: iitem.base64}, up, down)
          .then(messageId => {
            if (messageId === null) {
                failFileSend.push(item.fileName);
            } else {
                // ChatManager.pollMessage();
            }
            count--;
          }, err => {alert('err');d1.resolve(false);})
        }
      })
    });

    let check = function() {
      if (count) {
        setTimeout(check, 500);
      } else {
        d2.resolve(`文件发送完毕 --- 失败:${failFileSend.length && failFileSend.join(', ')}`)
      }
    }
    check();
  } else {
    d2.resolve(false)
  }

  $.when(d1, d2).done(function (v1, v2) {
    let output = [];
    v1 && output.push(v1);
    v2 && output.push(v2);
    dd.resolve(output);
  });

  return dd;
}

export function fileType(fileName) {
  let type = 2;
  const regs = [
    /(.*)\.(jpg|bmp|gif|ico|pcx|jpeg|tif|png|raw|tga|PNG)$/, // 图片
    /(.*)\.(mp3|wma|wav|ape|flac|ogg|aac)$/, // 音频
    /(.*)\.(wmv|asf|rm|rmvb|mov|avi|dat|mpg|mpeg|mp4)$/, // 视频
  ];
  for (let i = 0; i < regs.length; i++) {
    if (regs[i].test(fileName)) {
      type = 3 + i;
      break;
    }
  }
  return type;
}

export function fileExt(file){
	   	var filename=(file).replace(/.*(\/|\\)/, "");
			var fileExt=(/[.]/.exec(filename)) ? /[^.]+$/.exec(filename.toLowerCase()) : '';

			switch(fileExt[0]) {
				case 'txt': return '';
				case 'pdf' : return 'pdf';
				case 'ppt' : return 'p';
				case 'xls' : return 'x';
				case 'doc' :
				case 'docx' : return 'w';
				default    : return 'others';
			}
}

export function formatType(type, content) {
  // console.log(`type----${type}`)
  // console.log(`content----${content}`)
  switch (type) {
    case "2":
      return '[文件]'
    case "3":
      return '[图片]'
    case "4":
      return '[音频]'
    case "5":
      return '[视频]'
    default:
      return emoImgToRect(content);
  }
}
